#include "widget2.h"
#include "ui_widget2.h"
#include <QMessageBox>
#include <QDebug>

widget2::widget2(const QString &username,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::widget2),
    m_username(username)
{
    ui->setupUi(this);
    socket2 = new QTcpSocket(this);

    connect(socket2, &QTcpSocket::connected, this, &widget2::onConnected2);
    connect(socket2, &QTcpSocket::readyRead, this, &widget2::onReadyRead2);
    connect(socket2, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &widget2::onError2);

    socket2->connectToHost("192.168.159.131", 1234);

}

widget2::~widget2()
{
    delete ui;
}

void widget2::on_chaxun_clicked()
{
    QString word = ui->danci1->text();

    QString message = "INQUIRE\n";
    message += m_username + "\n" + word + "\n";
    socket2->write(message.toUtf8());

    qDebug() << "发送信息";
}

void widget2::on_pushButton_2_clicked()
{
    QString message = "HISTORY\n";
    message += m_username + "\n";
    socket2->write(message.toUtf8());

    qDebug() << "发送信息";

}

void widget2::onConnected2() {
    qDebug() << "已连接到服务器！";
    QString message = "LOGIN_IN\n";
    message += m_username + "\n";
    socket2->write(message.toUtf8());
}

void widget2::onReadyRead2() {
    QByteArray data = socket2->readAll();

    QDataStream stream(&data, QIODevice::ReadOnly);
    QString message;
    stream >> message;

    int spaceIndex = message.indexOf('\n'); // 寻找第一个空格的位置

    QString responseType = message.left(spaceIndex);
    QString Data = message.mid(spaceIndex + 1);

    qDebug() << "接收信息";

    if (responseType == "INQUIRE_SUCCESS") {
        ui->jieshi1->setText(Data);
    } else if (responseType == "INQUIRE_FAIL") {
        QMessageBox::warning(this, "提示", "查找失败");
    } else if (responseType == "HISTORY_SUCCESS") {
        QMessageBox::information(this, "历史记录", Data);
    } else if (responseType == "HISTORY_FAIL") {
        QMessageBox::warning(this, "提示", "打开历史记录失败");
    }
}

void widget2::onError2(QAbstractSocket::SocketError socketError) {
    qDebug() << "Socket错误:" << socketError;
}

void widget2::closeEvent(QCloseEvent *event) {
    // 发送关闭消息给服务器
    qDebug() << "关闭客户端";
    QString message = "CLOSE\n";
    message += m_username + "\n";
    socket2->write(message.toUtf8());

    QWidget::closeEvent(event);
    emit closed();
}
